import json
import re
import time

from django import http
from django.contrib.auth import login, authenticate, logout
from django.db import DatabaseError
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.users.models import User
from utils.response_code import RETCODE


class LoginGuideView(View):
    def get(self, request):
        return render(request, 'login_guide.htm')


class RegisterGuideView(View):
    def get(self, request):
        return render(request, 'register_guide.htm')


class LoginView(View):
    def get(self, request):
        return render(request, 'login.htm')

    def post(self, request):
        # 获取数据
        phone = request.POST.get("phone")
        password = request.POST.get('password')
        indexccode = request.POST.get('indexccode')

        # 验证数据
        if not all(phone):
            return http.JsonResponse({'url': 'login', 'code': RETCODE.NECESSARYPARAMERR, 'msg': '缺少参数'})
        if password:
            if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
                return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '请输入正确的密码'})
        if indexccode:
            if not re.match(r'^[0-9]{4}$', indexccode):
                return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '请输入正确的验证码'})

        # 用户对象
        user = ""

        if password:
            # 判断手机号或用户名，密码是否正确
            user = authenticate(username=phone, password=password)
            if user is None:
                return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '用户名或密码错误'})

        if indexccode:
            # 判断是否是手机号
            if not re.match(r'^1[3-9]\d{9}$', phone):
                return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '请输入正确的手机号'})

            # 判断验证码是否正确
            # if code != "":
            #     return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '请输入正确的验证码'})

            # 判断数据库中是否有此手机号
            user = User.objects.filter(mobile=phone).get()
            if user is None:
                return http.JsonResponse({'url': 'login', 'code': RETCODE.PARAMERR, 'msg': '未注册！请去注册！'})

        # 保持状态
        login(request, user)

        # json数据
        response = http.JsonResponse({'url': '/', 'code': RETCODE.OK, 'msg': '登录成功'})

        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.htm')

    def post(self, request):
        # 获取数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        code = request.POST.get('indexccode')

        # 验证数据
        if not all([mobile, code]):
            return http.JsonResponse({'url': 'register', 'code': RETCODE.NECESSARYPARAMERR, 'msg': '缺少参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'url': 'register', 'code': RETCODE.MOBILEERR, 'msg': '手机号格式错误'})

        if not re.match(r'^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{8,20}$', mobile):
            return http.JsonResponse({'url': 'register', 'code': RETCODE.PWDERR, 'msg': '密码格式有误(字母、数字或者符号,最短8位,最长20位)'})

        # if code != "":
        #     return http.HttpResponseBadRequest('请输入正确的验证码')

        # 保存注册数据
        try:
            # 用户名
            username = "jxydt_" + mobile
            user = User.objects.create_user(username=username, mobile=mobile, password=password)
        except DatabaseError:
            return http.JsonResponse({'url': 'register', 'code': RETCODE.DBERR, 'msg': "注册失败"})

        # 实现状态保持
        login(request, user)

        # 构建json
        response = http.JsonResponse({'url': '/', 'code': RETCODE.OK, 'msg': "注册成功"})

        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class LogoutView(View):
    def get(self, request):
        # 清理session
        logout(request)

        # 退出登录，重定向到登录页
        response = redirect(reverse('index:index'))

        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class RetrievePwdView(View):
    def get(self, request):
        # return render(request, 'retrieve_pwd.html')
        return render(request, 'pwd2222.htm')

    def post(self, request):
        # 获取数据
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        indexccode = request.POST.get('indexccode')

        # 验证信息
        if not all([mobile, password, password2, indexccode]):
            return http.JsonResponse({'url': 'retrievepwd', 'code': RETCODE.NECESSARYPARAMERR, 'msg': '缺少参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'url': 'retrievepwd', 'code': RETCODE.MOBILEERR, 'msg': '手机号格式错误'})
        if not re.match(r'^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{8,20}$', password):
            return http.JsonResponse({'url': 'retrievepwd', 'code': RETCODE.PWDERR, 'msg': '密码格式有误(字母、数字或者符号,最短8位,最长20位)'})
        if password != password2:
            return http.JsonResponse({'url': 'retrievepwd', 'code': RETCODE.PWDERR, 'msg': '密码不一致'})
        # if indexccode != "":
        #     return http.JsonResponse({'url': 'register', 'code': RETCODE.IMAGECODEERR, 'msg': '验证码错误'})

        # 更新新密码
        try:
            # 查询对象
            user = User.objects.get(mobile=mobile)
            user.set_password(password2)
            user.save()
        except Exception as e:
            # print('e', e)
            return http.JsonResponse({'url': 'register', 'code': RETCODE.PWDERR, 'msg': '密码重置失败'})

        # 5.退出登陆,删除登陆信息
        logout(request)

        # 6.跳转到登陆页面
        response = http.JsonResponse({'url': '/login', 'code': RETCODE.OK, 'msg': '密码重置成功'})

        response.delete_cookie('username')

        return response


class UserInfoView(View):
    def get(self, request):

        context = {
            'user': request.user,
            'updatetime': time.strftime("%Y-%m-%d %H:%M", time.localtime()),
        }

        return render(request, 'user_info.htm', context)

    def post(self, request):
        # 获取数据
        mobile = request.POST.get('mobile')
        code = request.POST.get('code')
        oldpwd = request.POST.get('oldpwd')
        newpwd = request.POST.get('newpwd')
        repwd = request.POST.get('repwd')

        # 验证
        if not all([mobile, newpwd, repwd]):
            return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.NECESSARYPARAMERR, 'msg': '缺少参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.MOBILEERR, 'msg': '手机号格式错误'})
        if not re.match(r'^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{8,20}$', newpwd):
            return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.PWDERR, 'msg': '密码格式有误(字母、数字或者符号,最短8位,最长20位)'})
        if newpwd != repwd:
            return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.PWDERR, 'msg': '密码不一致'})

        # if code:
        #     if code != "":
        #         return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.IMAGECODEERR, 'msg': '验证码错误'})

        # 3.检验旧密码是否正确
        if oldpwd:
            if not request.user.check_password(oldpwd):
                return http.JsonResponse({'url': 'userinfo', 'code': RETCODE.PWDERR, 'msg': '原密码错误'})

        # 更新新密码
        try:
            request.user.set_password(newpwd)
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'url': '/login', 'code': RETCODE.PWDERR, 'msg': '密码修改失败'})

        # 5.退出登陆,删除登陆信息
        logout(request)

        # 6.跳转到登陆页面
        response = http.JsonResponse({'url': '/login', 'code': RETCODE.OK, 'msg': '密码重置成功，正在跳转登录！'})

        response.delete_cookie('username')

        return response
